package com.lry.router;

import com.lry.protocol.RpcInvocation;
import com.lry.proxy.Invoker;
import com.lry.proxy.RpcInvoker;
import com.lry.rpc.netty.client.ChannelWrapper;
import com.lry.spi.LoadLevel;

import java.util.List;
import java.util.Random;


@LoadLevel(name = "random")
public class RandomRouter implements Router {

    Random random = new Random();

    @Override
    public Invoker select(List<Invoker> invokers, RpcInvocation rpcInvocation) {
        int totalWeight = 0;
        for (Invoker invoker : invokers) {
            totalWeight += invoker.getWeight();
        }

        int pos = random.nextInt(totalWeight);

        for (Invoker invoker : invokers) {
            if(pos<invoker.getWeight()){
                return invoker;
            }
            pos -= invoker.getWeight();
        }

        return null;
    }
}
